package com.ruoyi.hxf.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.DataBaseHelper;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StreamUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.hxf.domain.Education;
import com.ruoyi.hxf.domain.Message;
import com.ruoyi.hxf.domain.Subject;
import com.ruoyi.hxf.mapper.MessageMapper;
import com.ruoyi.hxf.mapper.TabMapper;
import com.ruoyi.hxf.service.IMessageService;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 信息 服务层实现
 *
 * @author hxf
 */
@RequiredArgsConstructor
@Service
public class MessageServiceImpl implements IMessageService {
    private final MessageMapper messageMapper;

    /**
     * 新增信息
     *
     * @param message
     * @return 结果
     */
    @Override
    public int insertMessage(Message message) {
        return messageMapper.insertMessage(message);
    }

    /**
     * 获取自己的发送消息列表或者接收的消息列表（适用于手机端和电脑端）
     *
     * @param message 信息
     * @return 信息集合
     */
    @Override
    public List<Message> selectHomeWorkMessageList(Message message) {
        return messageMapper.selectHomeWorkMessageList(message);
    }

    /**
     * 获取自己的发送消息列表或者接收的消息列表（适用于手机端和电脑端）
     *
     * @param message 信息
     * @return 信息集合
     */
    @Override
    public TableDataInfo<Message> selectPageHomeWorkMessageList(Message message, PageQuery pageQuery) {
        LambdaQueryWrapper<Message> lqw = new LambdaQueryWrapper<Message>()
            .eq(StringUtils.isNotBlank(message.getCreateBy()), Message::getCreateBy, message.getCreateBy())
            .eq(StringUtils.isNotBlank(message.getReceiverId()), Message::getReceiverId, message.getReceiverId())
            .eq(message.getMsgStatus() != null, Message::getMsgStatus, message.getMsgStatus())
            .eq(Message::getIsDelete, 0)
            .last("order by create_time desc");
        Page<Message> page = messageMapper.selectPageHomeWorkMessageList(pageQuery.build(), lqw);
        return TableDataInfo.build(page);
    }

    @Override
    public List<Message> selectMessageList(Message message) {
        return messageMapper.selectMessageList(message);
    }

    /**
     * 删除收到的消息信息（逻辑删除）
     *
     * @param msgIds 需要删除的消息ID
     * @return
     */
    @Override
    public int deleteMessageByIds(Long[] msgIds,int i) {
        return messageMapper.deleteMessageByIds(msgIds,i);
    }

    /**
     * 查询置顶的数量
     *
     * @return
     */
    @Override
    public Integer selectToppingQuantity() {
        return messageMapper.selectToppingQuantity();
    }

    /**
     * 设置置顶的排序
     *
     * @param msgId 消息ID
     * @param i     等级
     */
    @Override
    public void updateToppingQuantity(Long msgId, int i) {
        messageMapper.updateToppingQuantity(msgId, i);
    }

    /**
     * 标记是否读取
     *
     * @param msgId 消息ID
     * @param i     状态
     */
    @Override
    public void updateReadStatus(Long msgId, int i) {
        messageMapper.updateReadStatus(msgId, i);
    }

    /**
     * 查询班级发送的信息列表
     *
     * @param message
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<Message> queryPageList(Message message, PageQuery pageQuery) {
        Page<Message> page = messageMapper.selectPageList(pageQuery.build(), this.buildQueryWrapper(message));
        return TableDataInfo.build(page);
    }

    /**
     * 查询已读的人数
     *
     * @param similarMessage
     * @return
     */
    @Override
    public Long selectSimilarMessageList(Message similarMessage) {
        return messageMapper.selectCount(new LambdaQueryWrapper<Message>()
            .eq(StringUtils.isNotBlank(similarMessage.getMsgTitle()), Message::getMsgTitle, similarMessage.getMsgTitle())
            .eq(StringUtils.isNotBlank(similarMessage.getMsgContent()), Message::getMsgContent, similarMessage.getMsgContent())
            .eq(StringUtils.isNotBlank(similarMessage.getRemark()), Message::getRemark, similarMessage.getRemark())
            .eq(StringUtils.isNotBlank(similarMessage.getMsgAvatar()), Message::getMsgAvatar, similarMessage.getMsgAvatar())
            .eq(StringUtils.isNotBlank(similarMessage.getCreateBy()), Message::getCreateBy, similarMessage.getCreateBy())
            .eq(similarMessage.getReadStatus()!=null, Message::getReadStatus, similarMessage.getReadStatus())
            .eq(similarMessage.getCreateTime()!=null, Message::getCreateTime, similarMessage.getCreateTime())
            .eq(similarMessage.getMsgStatus()!=null, Message::getMsgStatus, similarMessage.getMsgStatus())
        );
    }

    /**
     * 撤回消息信息
     * @param msgIds
     * @return
     */
    @Override
    public int updateMessageByIds(Long[] msgIds) {
        for (Long msgId : msgIds) {
            Message message = messageMapper.selectOne(new LambdaQueryWrapper<Message>()
                .eq(msgId!=null, Message::getMsgId, msgId)
                .select(Message.class,info -> !info.getColumn().equals("read_number")));
            List<Message> messages = messageMapper.selectList(new LambdaQueryWrapper<Message>()
                .eq(StringUtils.isNotBlank(message.getMsgTitle()), Message::getMsgTitle, message.getMsgTitle())
                .eq(StringUtils.isNotBlank(message.getMsgContent()), Message::getMsgContent, message.getMsgContent())
                .eq(StringUtils.isNotBlank(message.getRemark()), Message::getRemark, message.getRemark())
                .eq(StringUtils.isNotBlank(message.getMsgAvatar()), Message::getMsgAvatar, message.getMsgAvatar())
                .eq(StringUtils.isNotBlank(message.getCreateBy()), Message::getCreateBy, message.getCreateBy())
                .eq(message.getCreateTime() != null, Message::getCreateTime, message.getCreateTime())
                .eq(message.getMsgStatus() != null, Message::getMsgStatus, message.getMsgStatus())
                .eq(Message::getIsDelete,0)
                .select(Message.class,info -> !info.getColumn().equals("read_number")));
            List<String> list=new ArrayList();
            for (Message message1 : messages) {
                list.add(String.valueOf(message1.getMsgId()));
            }
            Long[] num = new Long[list.size()];
            for (int idx = 0; idx < list.size(); idx++) {
                num[idx] = Long.parseLong(list.get(idx));
            }
            messageMapper.deleteMessageByIds(num,2);
        }
        return 1;
    }

    private Wrapper<Message> buildQueryWrapper(Message message) {
        Map<String, Object> params = message.getParams();
        QueryWrapper<Message> wrapper = Wrappers.query();
        wrapper.eq("is_delete", 0)
            .eq(message.getMsgStatus() != null, "msg_status", message.getMsgStatus())
            .eq(StringUtils.isNotBlank(message.getRemark()),"remark",LoginHelper.getUsername())
            .eq(StringUtils.isNotBlank(message.getCreateBy()), "create_by", message.getCreateBy())
            .eq(message.getReceiverId() != null, "receiver_id", message.getReceiverId())
            .like(StringUtils.isNotBlank(message.getMsgTitle()), "msg_title", message.getMsgTitle())
            .between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
                "create_time", params.get("beginCreateTime"), params.get("endCreateTime"))
            .or()
            .eq("is_delete", 2)
            .eq(message.getMsgStatus() != null, "msg_status", message.getMsgStatus())
            .eq(StringUtils.isNotBlank(message.getRemark()),"remark",LoginHelper.getUsername())
            .eq(StringUtils.isNotBlank(message.getCreateBy()), "create_by", message.getCreateBy())
            .eq(message.getReceiverId() != null, "receiver_id", message.getReceiverId())
            .like(StringUtils.isNotBlank(message.getMsgTitle()), "msg_title", message.getMsgTitle())
            .between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
                "create_time", params.get("beginCreateTime"), params.get("endCreateTime"))
            .last("order by update_time desc,create_time desc");
        return wrapper;
    }
}
